<template>
  <!-- 物流付款单 -->
  <VPage>
    <VTable ref="tableRef" v-bind="tableOptins">
      <template #form="{ form }">
        <XForm
          :fieldList="fieldList"
          :formOption="optionsDataAll"
          :formData="form"
        >
        </XForm>
      </template>
      <template #toolbar_btns>
        <VActionBar :actions="actions" />
      </template>
      <template #logistics_pay_number="{ row }">
        <el-link type="primary" @click="handleDetail(row.id)">
          {{ row?.logistics_pay_number }}
        </el-link>
      </template>
      <template #pay_receipts="{ row }">
        <div v-if="row?.pay_receipts?.length">
          <el-link
            type="primary"
            v-for="(item, index) in row?.pay_receipts"
            :key="index"
            @click="handleLink(item.oss_path)"
          >
            {{ item?.source_name || "-" }}
          </el-link>
        </div>
      </template>
      <template #operation="{ row }">
        <div class="flex items-center">
          <el-button
            link
            type="primary"
            @click="handleDetail(row.id)"
            v-hasPermi="[financeManageAuthList.bills_payment.details]"
          >
            详情
          </el-button>
          <el-button
            v-if="[0, 2]?.includes(row?.audit_status)"
            link
            type="primary"
            @Click="handleEdit(row.id)"
            v-hasPermi="[financeManageAuthList.bills_payment.edit]"
          >
            编辑
          </el-button>
          <el-dropdown
            @command="
              ($event) => {
                handleCommand($event, row);
              }
            "
          >
            <SvgIcon class="ml-[16px]" icon-class="more" />
            <template #dropdown>
              <el-dropdown-menu v-matomo>
                <el-dropdown-item
                  v-for="(item, index) in operateList"
                  :key="index"
                  :disabled="
                    !item?.isShow?.includes(row?.audit_status) ||
                    !isPermission(item.permission)
                  "
                  :command="item.label"
                  >{{ item?.label }}</el-dropdown-item
                >
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </template>
    </VTable>
    <DerivedCenter ref="DerivedCenterRef"></DerivedCenter>
    <add
      v-model="addDialog"
      :id="addId"
      :type="addType"
      @refresh="refresh"
      @close="
        addId = '';
        addType = '';
      "
    />
    <Log
      dialog
      v-model="logVisible"
      :autoLoad="false"
      tag="finance.logistics-pay-order"
      :business_id="logId"
      @close="logId = null"
    />
    <ConfirmInput
      title="审核"
      class="w-[500px]"
      confirmButtonText="确认"
      v-model="approvalVisible"
      :loading="loading"
      :field-options="approvalOptions"
      :rules="approvalRules"
      @submit="handleApprovalReq"
    />
    <detail v-model="detailDialog" :id="detailId" @close="detailId = ''" />
    <Batchprint v-model="printVisible" :id="printIds" @close="printIds = []" />
  </VPage>
</template>
<script setup lang="jsx">
import { ElMessage } from "element-plus";
import add from "./add/index.vue";
import XForm from "@/components/XForm/index.vue";
import { financeManageAuthList } from "@/Auth/finance-manage.js";
import DerivedCenter from "@/components/DerivedCenter/index.vue";
import { config_name } from "@/config/export.js";
import ConfirmInput from "@/components/ConfirmInput/index.vue";
import { useEnumSelect } from "@/hooks";
import { logisticsList } from "@/api/index.js";
import Batchprint from "./components/Batchprint/index.vue";
import { getTableSelectRow, getTableSelect } from "@/hooks/tool.js";
import { handleLink } from "@/hooks/tool.js";
import { isPermission } from "@/hooks/permission.js";
import SvgIcon from "@/components/SvgIcon/index.vue";
import {
  getLogisticsPayOrder,
  submitLogisticsPayOrder,
  cancelLogisticsPayOrder,
  payLogisticsPayOrder,
  auditLogisticsPayOrder,
} from "./api/index.js";
import detail from "./detail/index.vue";
import Log from "@/components/Log/index.vue";
import { emunData, fieldList } from "./index.js";
const router = useRouter();
const tableRef = ref();
const { proxy } = getCurrentInstance();
const tableOptins = reactive({
  formConfig: {
    data: {
      number: "",
      pay_main_company: "",
      logistics_id: [],
      audit_status: "",
      dateRange: { type: "pay_time", value: [], range: false },
    },
  },
  tooltipConfig: {
    showAll: false,
  },
  isToggle: true,
  columns: [
    { fixed: "left", width: 50, type: "checkbox" },
    {
      fixed: "left",
      title: "物流付款单号",
      minWidth: 150,
      field: "logistics_pay_number",
      slots: { default: "logistics_pay_number" },
    },
    {
      fixed: "left",
      title: "物流商名称",
      width: 260,
      field: "logistics_name",
    },
    {
      title: "收款单位",
      width: 220,
      field: "collect_account_name",
    },
    { title: "付款方式", width: 120, field: "pay_type" },
    { title: "收款账号", width: 160, field: "collect_back_account" },
    { title: "开户行", width: 220, field: "collect_bank_name" },
    { title: "应付金额", width: 140, field: "pay_amount_cny" },
    { title: "申付金额", width: 140, field: "req_amount_cny" },
    { title: "扣款金额", width: 140, field: "cut_amount_cny" },
    { title: "付款币种", width: 100, field: "pay_currency" },
    {
      title: "付款主体公司",
      width: 220,
      field: "pay_main_company_name",
    },
    {
      title: "实付总金额",
      width: 140,
      field: "pay_total_amount_cny",
    },
    {
      title: "汇率",
      width: 100,
      field: "exchange_rate",
      formatter: ["formatNumberData", 4],
    },
    {
      title: "结算周期",
      width: 100,
      field: "settle_type",
    },

    {
      title: "付款凭证",
      width: 220,
      slots: { default: "pay_receipts" },
    },
    {
      title: "来源",
      width: 120,
      field: "source_type",
      slots: {
        default: ({ row }) => {
          return (
            <div>
              <div>{row?.source_type || "-"}</div>
              <div>{row?.bill_number || "-"}</div>
            </div>
          );
        },
      },
    },
    {
      title: "",
      width: 190,
      field: "",
      slots: {
        header: () => {
          return (
            <div>
              <div>申请人</div>
              <div>申请付款时间</div>
            </div>
          );
        },
        default: ({ row }) => {
          return (
            <div>
              <div>{row?.create_user || "-"}</div>
              <div>{row?.create_time || "-"}</div>
            </div>
          );
        },
      },
    },
    {
      title: "",
      width: 190,
      field: "channel_name",
      slots: {
        header: () => {
          return (
            <div>
              <div>付款人</div>
              <div>付款时间</div>
            </div>
          );
        },
        default: ({ row }) => {
          return (
            <div>
              <div>{row?.pay_user || "-"}</div>
              <div>{row?.pay_time || "-"}</div>
            </div>
          );
        },
      },
    },
    {
      title: "",
      width: 200,
      field: "channel_name",
      slots: {
        header: () => {
          return (
            <div>
              <div>物流备注</div>
              <div>财务备注</div>
            </div>
          );
        },
        default: ({ row }) => {
          return (
            <div>
              <VText value={row?.logistics_remark} line={2}></VText>
              <VText value={row?.finance_remark} line={2}></VText>
            </div>
          );
        },
      },
    },
    {
      title: "状态",
      width: 100,
      field: "audit_status_label",
    },
    {
      fixed: "right",
      title: "操作",
      width: 160,
      slots: { default: "operation" },
    },
  ],
  proxyConfig: {
    autoLoad: false, // 是否自动加载查询数据
    props: {
      result: "data",
      total: "total",
    },
    ajax: {
      query: ({ page, form }) => {
        return getLogisticsPayOrder({ ...form, ...page }).then((res) => {
          return {
            data: res.data,
            total: res.total,
          };
        });
      },
    },
  },
});

const detailDialog = ref(false);
const detailId = ref("");
const handleDetail = (item) => {
  detailId.value = item;
  detailDialog.value = true;
};

const addType = ref("");
const addId = ref("");
const addDialog = ref(false);
const handleAdd = () => {
  addDialog.value = true;
};
const handleEdit = (id) => {
  addId.value = id;
  addDialog.value = true;
};

//导出
const DerivedCenterRef = ref();
const handleExport = async () => {
  let condition = getTableSelectRow(tableRef.value);
  DerivedCenterRef.value.open({
    tag_name: config_name["finance_manage"]["logistics_pay_order"],
    condition,
  });
};
const refresh = () => {
  tableRef?.value.$table.commitProxy("query");
};
const printIds = ref([]);
const printVisible = ref(false);
//批量打印
const handleBatchPrint = () => {
  const rows = getTableSelect(tableRef.value);
  if (!rows.length) return ElMessage.warning("请至少选择一条数据！");
  printVisible.value = true;
  printIds.value = rows;
};

const { options: optionsData } = useEnumSelect({
  params: [
    "finance_settle_type",
    "finance_charge_status",
    "finance_lpo_pay_main_company",
    "finance_lpo_audit_status",
  ],
});
//获取物流商
const optionsData1 = ref({});
const getlogistics = () => {
  logisticsList({}).then((res) => {
    optionsData1.value.logistics = res?.data || [];
  });
};
getlogistics();
const optionsDataAll = computed(() =>
  Object.assign({}, optionsData.value, optionsData1.value)
);

//提交
const handleSubmit = (item) => {
  proxy?.confirm({
    title: "提示",
    content: <p>确认提交该条数据？</p>,
    beforeClose: async (action, instance, done) => {
      if (action === "confirm") {
        try {
          instance.confirmButtonLoading = true;
          instance.confirmButtonText = "处理中..";
          const { code, message } = await submitLogisticsPayOrder({
            id: item?.id,
          });
          if (code !== 200) {
            ElMessage.warning(message);
            return;
          }
          ElMessage.success("提交成功");
        } catch (e) {
          console.error(e);
        } finally {
          instance.confirmButtonLoading = false;
          done();
          refresh();
        }
      } else {
        done();
      }
    },
  });
};
const handlePayment = (val) => {
  addId.value = val.id;
  addType.value = "payment";
  addDialog.value = true;
};
const handlePrintPayment = () => {};

//日志
const logVisible = ref(false);
const logId = ref(null);
const handleLog = (item) => {
  logId.value = item?.id;
  logVisible.value = true;
};
const approvalVisible = ref(false);
const loading = ref(false);
const auditData = ref({});
const handleAudit = (item) => {
  approvalVisible.value = true;
  auditData.value = item;
};
const handleApprovalReq = async (formValues) => {
  const { id, flage } = auditData.value;
  const obj = {
    id,
    audit_obj: emunData["auditList"][flage],
    ...formValues,
  };
  try {
    loading.value = true;
    const { code, message } = await auditLogisticsPayOrder(obj);
    if (code !== 200) {
      ElMessage.warning(message);
      return;
    }
    ElMessage.success("操作成功");
    auditData.value = null;
    approvalVisible.value = false;
    refresh();
  } catch (e) {
  } finally {
    loading.value = false;
  }
};
const approvalOptions = [
  {
    label: "审核状态",
    field: "audit",
    type: "radio",
    style: { width: "100%" },
    options: {
      data: [
        { label: "通过", value: "pass" },
        { label: "驳回", value: "rejected" },
      ],
    },
    itemProps: {
      popperAppendToBody: true,
      teleported: true,
    },
  },
  {
    label: "驳回原因",
    field: "remark",
    type: "textarea",
    style: { marginTop: "10px" },
    autosize: { minRows: 4, maxRows: 8 },
    show: ({ model }) => model.audit === "rejected",
  },
];
const approvalRules = {
  audit: [{ required: true, message: "请选择审核状态", trigger: "blur" }],
};
//作废
const handleCancel = (item) => {
  proxy?.confirm({
    title: "提示",
    content: <p>确认作废该条数据？</p>,
    beforeClose: async (action, instance, done) => {
      if (action === "confirm") {
        try {
          instance.confirmButtonLoading = true;
          instance.confirmButtonText = "处理中..";
          const { code, message } = await cancelLogisticsPayOrder({
            id: item?.id,
          });
          if (code !== 200) {
            ElMessage.warning(message);
            return;
          }
          ElMessage.success("作废成功");
        } catch (e) {
          console.error(e);
        } finally {
          instance.confirmButtonLoading = false;
          done();
          refresh();
        }
      } else {
        done();
      }
    },
  });
};

const handleCommand = (e, row) => {
  const _item = operateList.find((n) => n.label === e);
  _item?.fn?.(JSON.parse(JSON.stringify(Object.assign({}, row, { flage: e }))));
};

const operateList = [
  {
    label: "提交",
    fn: handleSubmit,
    isShow: [0, 2],
    permission: [financeManageAuthList.bills_payment.submit],
  },
  {
    label: "付款",
    fn: handlePayment,
    isShow: [3],
    permission: [financeManageAuthList.bills_payment.payment],
  },
  // {
  //   label: "打印付款单",
  //   fn: () => ElMessage.warning("需要集成暂时todo"),
  //   isShow: [0, 1, 2, 6, 7, 8, 9, 10, 11],
  //   permission: [financeManageAuthList.bills_payment.payment],
  // },
  {
    label: "作废",
    fn: handleCancel,
    isShow: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11],
    permission: [financeManageAuthList.bills_payment.cancel],
  },
  {
    label: "日志",
    fn: handleLog,
    isShow: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11],
    permission: [financeManageAuthList.bills_payment.log],
  },
  {
    label: "物流经理审核",
    fn: handleAudit,
    isShow: [6],
    permission: [financeManageAuthList.bills_payment.LSMaudit],
  },
  {
    label: "供应链总监审核",
    fn: handleAudit,
    isShow: [7],
    permission: [financeManageAuthList.bills_payment.SCDaudit],
  },
  {
    label: "应付会计审核",
    fn: handleAudit,
    isShow: [8],
    permission: [financeManageAuthList.bills_payment.ACCOUNTANTSaudit],
  },
  {
    label: "财务副经理审核",
    fn: handleAudit,
    isShow: [9],
    permission: [financeManageAuthList.bills_payment.DFMaudit],
  },
  {
    label: "财务总监审核",
    fn: handleAudit,
    isShow: [10],
    permission: [financeManageAuthList.bills_payment.CFOaudit],
  },
  {
    label: "CEO审核",
    fn: handleAudit,
    isShow: [11],
    permission: [financeManageAuthList.bills_payment.CEOaudit],
  },
];
const actions = [
  {
    label: "新增",
    icon: "add2",
    type: "primary",
    fn: handleAdd,
    permission: [financeManageAuthList.bills_payment.add],
  },
  {
    label: "批量打印",
    fn: handleBatchPrint,
    permission: [financeManageAuthList.bills_payment.payment],
  },
  {
    label: "导出",
    right: true,
    dkicon: "icon-Upload",
    fn: handleExport,
    permission: [financeManageAuthList.bills_payment.export],
  },
];
</script>

<style lang="scss" scoped></style>
